package com.learn.rabbitmq.four;

import com.learn.rabbitmq.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.rabbitmq.client.MessageProperties;

import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

/**
 * 发布确认模式(生产者)
 *
 * 1.单个确认         使用的时间 比较效率
 * 2.批量确认
 * 3.异步批量确认
 */
public class ConfigMessage {

    public static final int COUNT = 1000;

    public static void main(String[] args) throws Exception {
        //1.单个确认
        //publishMessageIndividually(); //1270
        //2.批量确认
       // publishMessageBatch();//68
        //3.异步批量确认
        publishMessageAsync();//41

    }

    //1.单个确认
    public static void publishMessageIndividually() throws Exception {

        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);

        //开启发布确认
        channel.confirmSelect();
        long begin = System.currentTimeMillis();

        //
        for (int i = 0; i < COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));
            //单个消息就马上进行发布确认
            boolean flag = channel.waitForConfirms();
            if (flag) {
                System.out.println("ok");
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("发布" + COUNT + "用时" + (end - begin));

    }
    //2.批量确认

    public static void publishMessageBatch() throws Exception {

        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);

        //开启发布确认
        channel.confirmSelect();
        long begin = System.currentTimeMillis();

        //批量发送数据
        for (int i = 1; i <= COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));

            //批量
            if (i % 100 == 0) {
                boolean flag = channel.waitForConfirms();
                if (flag) {
                    System.out.println("ok");
                }
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("发布" + COUNT + "用时" + (end - begin));

    }

    //3.异步批量确认
    public static void publishMessageAsync() throws Exception {

        Channel channel = RabbitMqUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName, true, false, false, null);

        //开启发布确认
        channel.confirmSelect();
        /**
         * 线程安全有序的一个哈希表 适用于高并发的情况下
         * 1.轻松的将序号和消息进行关联
         * 2.轻松批量删除条目 通过序号
         * 3.支持高并发(多线程)
         */
        ConcurrentSkipListMap<Long,String> concurrentSkipListMap=new ConcurrentSkipListMap();

        /**
         * long deliveryTag 消息的标记
         * boolean multiple 是否为批量确认
         */
        ConfirmCallback ackCallback = (deliveryTag, multiple) -> {
            if(multiple) {
                //2:删除已经确认的消息
                ConcurrentNavigableMap<Long, String> headMap = concurrentSkipListMap.headMap(deliveryTag);
                headMap.clear();
            }else {
                concurrentSkipListMap.remove(deliveryTag);
            }
            System.out.println("确认的消息："+deliveryTag);
        };
        ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
            //3:打印未确认的消息
            String message = concurrentSkipListMap.get(deliveryTag);
            System.out.println("未确认的消息："+deliveryTag+"---消息是:"+message);
        };
        //准备消息的监听器  确认哪些消息成功，哪些消息失败
        /**
         * ConfirmCallback ackCallback  监听成功的
         * ConfirmCallback nackCallback 监听失败的
         */
        channel.addConfirmListener(ackCallback,nackCallback);//异步通知

        long begin = System.currentTimeMillis();
        //批量发送数据 异步
        for (int i = 1; i <= COUNT; i++) {
            String message = i + "";
            channel.basicPublish("", queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));
            //1:记录消息总和
            concurrentSkipListMap.put(channel.getNextPublishSeqNo(),message);

        }
        long end = System.currentTimeMillis();
        System.out.println("发布" + COUNT + "用时" + (end - begin));

    }
}
